<template>
    <div>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入员工姓名" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
                    <el-option v-for="item in genderOption" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="入职时间">
                <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <div class="topBtn">
            <el-button type="primary" @click="addEmp">+ 新增员工</el-button>
            <el-button type="primary" @click="deleteEmps">- 批量删除</el-button>
        </div>
        <el-table ref="table" :data="tableData" tooltip-effect="dark" style="width: 100%" height="70vh"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120" align="center">
            </el-table-column>
            <el-table-column label="图像" width="120" align="center">
                <template slot-scope="scope">
                    <el-image style="width: 80px; height: 80px" :src="scope.row.image" fit="fill"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="性别" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.gender == 1 ? '男' : scope.row.gender == 2 ? '女' : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="职位" align="center">
                <template slot-scope="scope">
                    <span>
                        {{ jobMapping[scope.row.job ? scope.row.job : 0].label }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="入职日期" prop="entrydate" align="center">
            </el-table-column>
            <el-table-column label="最后操作时间" align="center">
                <template slot-scope="scope">
                    <span>
                        {{ scope.row.updateTime.split("T")[0] }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pageBox">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 50, 100]" :page-size="10"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="40%" @close="handleClose" v-dialogDrag v-dialogDragWidth dialogDragHeight>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" placeholder="请输入用户名，2-20字符，不可重复"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="员工姓名" prop="name">
                        <el-input v-model="form.name" placeholder="请输入员工姓名，2-10个字"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="form.gender" placeholder="请选择">
                            <el-option label="男" :value="1"></el-option>
                            <el-option label="女" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="图像" prop="image">
                        <ImageUpload :limit="1" :value="form.image" v-if="dialogVisible" @input="successImage">

                        </ImageUpload>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="职位" prop="job">
                        <el-select v-model="form.job" placeholder="请选择">
                            <el-option label="班主任" :value="1"></el-option>
                            <el-option label="讲师" :value="2"></el-option>
                            <el-option label="学工主管" :value="3"></el-option>
                            <el-option label="教研主管" :value="4"></el-option>
                            <el-option label="咨询师" :value="5"></el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="入职日期" prop="entrydate">
                        <el-date-picker v-model="form.entrydate" type="date" placeholder="选择日期"
                            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="部门" prop="deptId">
                        <el-select v-model="form.deptId" placeholder="请选择">
                            <el-option :label="item.name" :value="item.id" v-for="(item, index) in deptList"
                                :key="index"></el-option>

                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>

export default {
    data() {
        return {
            queryParams: {
                name: null,
                gender: null,
                entryStartTime: null,
                entryEndtime: null,
                pageNum: 1,
                pageSize: 10
            },
            // 弹框标题
            title: '添加员工',
            // 表单
            form: {
                id: null,
                username: '',
                name: '',
                gender: null,
                image: null,
                job: null,
                entrydate: null,
                deptId: null
            },
            // 部门列表
            deptList: [],
            // 验证规则
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入员工姓名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'blur' },
                ]

            },
            // 对话框
            dialogVisible: false,
            // 当前页码
            currentPage: 1,
            // 列表总条数
            total: 0,
            // 职位mapping
            jobMapping: [
                {
                    label: '-',
                    value: 0
                },
                {
                    label: '班主任',
                    value: 1
                },
                {
                    label: '讲师',
                    value: 2
                },
                {
                    label: '学工主管',
                    value: 3
                },
                {
                    label: '教研主管',
                    value: 4
                },
                {
                    label: '咨询师',
                    value: 5
                }
            ],
            // 列表数据
            tableData: [],
            // 入职日期范围
            dateRange: '',
            // 选中的表格项
            ids: [],
            genderOption: [
                {
                    value: 1,
                    label: '男'
                },
                {
                    value: 2,
                    label: '女'
                }
            ]
        }
    },
    computed: {

    },
    created() {
        this.getDeptList()
        this.getlist()
    },
    methods: {
        successImage(e) {
            this.form.image = e
        },
        async getlist() {

            try {
                const { data: res } = await this.$api.getEmpList(Object.assign(this.queryParams, { beginTime: this.dateRange ? this.dateRange[0] : null, endTime: this.dateRange ? this.dateRange[1] : null }))
                if (res.code == 1) {
                    this.tableData = res.data.rows
                    this.total = res.data.total
                }
            } catch (error) {
                console.log(error);

            }
        },
        async getDeptList() {
            try {
                const { data: res } = await this.$api.getList();
                if (res.code == 1) {
                    this.deptList = res.data
                }
            } catch (error) {
                console.log(error);
            }
        },
        addEmp() {
            this.dialogVisible = true
        },
        deleteEmps() {
            if (this.ids.length) {
                this.$confirm(`此操作将删除选中的数据, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const { data: res } = await this.$api.deleteEmps(this.ids)
                    if (res.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        this.getlist();
                    }
                }).catch(() => {

                });
            }
        },
        handleEdit(index, val) {
            this.dialogVisible = true
            this.$api.getEmpById(val.id).then(res => {
                if(res.data.code == 1) {
                    Object.keys(this.form).forEach(key => {
                        if(key in res.data.data) {
                            this.form[key] = res.data.data[key]
                        }
                    })
                }
                
            })

        },
        handleDelete(index, val) {
            this.$confirm(`此操作将删除${val.name}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {

                const { data: res } = await this.$api.deleteEmps([val.id])
                if (res.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    this.getlist();
                }
            }).catch(() => {

            });
        },
        handleSelectionChange(val) {
            this.ids = val.map(item => item.id)
        },
        resetQuery() {
            this.dateRange = []
            this.$refs['queryForm'].resetFields()
            this.getlist()

        },
        handleQuery() {
            this.getlist();
        },
        handleSizeChange(val) {
            this.queryParams.pageSize = val
            this.getlist();

        },
        handleCurrentChange(val) {
            this.queryParams.pageNum = val
            this.getlist();

        },
        closeDialog() {
            this.dialogVisible = false
            this.reset()
        },
        submit() {
            this.$refs['form'].validate(async (value) => {
                if(value) {
                    if(this.form.id) {
                        const {data: res} = await this.$api.updateEmp(this.form)
                        if(res.code == 1) {
                            this.$message({
                                message: "修改员工成功",
                                type: 'success'
                            })
                            this.dialogVisible = false
                            this.getlist()
                        }
                        
                    }else {
                        const {data: res} = await this.$api.addEmp(this.form)
                        if(res.code == 1) {
                            this.$message({
                                message: "添加员工成功",
                                type: 'success'
                            })
                            this.dialogVisible = false
                            this.getlist()
                        }
                    }
                }
            })
        },
        handleClose() {
            this.dialogVisible = false
            this.reset()
        },
        // 表单重制
        reset() {
            this.form = {
                id: null,
                username: '',
                name: '',
                gender: null,
                image: null,
                job: null,
                entrydate: null,
                deptId: null
            };
            this.$refs("form").resetFields();
        },
    }
}
</script>

<style lang="scss" scoped>


.el-col {
    border-radius: 4px;
}

.bg-purple-dark {
    background: #99a9bf;
}

.bg-purple {
    background: #d3dce6;
}

.bg-purple-light {
    background: #e5e9f2;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
}

.topBtn {
    margin-bottom: 20px;
}

.pageBox {
    margin-top: 20px;
    text-align: center;
}
</style>